package com.librariy.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageLoader {
    private static final String TAG = "ImageCachedLoader";
    public static ExecutorService cachedThreadPool = Executors.newFixedThreadPool(5);
    private static File mCacheDir=null;
    public static void displayImage(final String mUrl, final ImageView mImageView, final int defaultImg) {
        if (mImageView == null | mUrl == null)
            return;
        if(defaultImg>0) mImageView.setImageResource(defaultImg);
        mImageView.post(new Runnable() {
            @Override
            public void run() {
                ImageLoader.startImageLoad(mUrl, mImageView, defaultImg);
            }
        });
    }
    private static void startImageLoad(final String mUrl, final ImageView mImageView, int defaultImg) {
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                ImageLoader.mCacheDir=ZorenCache.initCacheDir(mImageView.getContext(),"image_loader_cache",mCacheDir);
                for(int i=0;i<2;i++){
                    try {
                        Bitmap mBitmap = ImageLoader.getBitmap(mUrl, mImageView.getMeasuredWidth(), mImageView.getMeasuredHeight());
                        ImageLoader.postImageLoad(mImageView,mBitmap);
                        if(mBitmap!=null) break;
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    private static void postImageLoad(final ImageView mImageView,final Bitmap mBitmap){
        if (mImageView == null | mBitmap == null)
            return;
        mImageView.post(new Runnable() {
            @Override
            public void run() {
                mImageView.setImageBitmap(mBitmap);
            }
        });
    }
    private static Bitmap getBitmap(String mUrl, float width, float height) {
        File image=new File(mCacheDir, StrUtil.getMd5String(mUrl,"NULL"));
        try {
            ZorenCache.clearCacheDir(mCacheDir);
            if(!image.isFile()){
                Log.d(TAG, String.format("ThreadID=%s； getBitmap(mUrl=%s, width=%s, height=%s); \n+++ Download and Save File to[%s]", Thread.currentThread().getId(), mUrl,width,height,image.getAbsolutePath()));
                BufferedInputStream in = new BufferedInputStream(new URL(mUrl).openStream());
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(image));
                byte buff[]=new byte[1024];
                int len=0;
                while((len=in.read(buff))>0){
                    out.write(buff, 0, len);
                }
                out.close();
                in.close();
            }else{
                Log.d(TAG, String.format("ThreadID=%s； getBitmap(mUrl=%s, width=%s, height=%s); \n--- Use Cached File[%s]", Thread.currentThread().getId(), mUrl,width,height,image.getAbsolutePath()));
                image.setLastModified(System.currentTimeMillis());
            }
            if(width==0||height==0){
                width=height=100;
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig=Bitmap.Config.RGB_565;
            options.inPurgeable=true;
            options.inPurgeable=true;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(image.getAbsolutePath(), options);
            options.inJustDecodeBounds = false;            
            int inSampleSizeWidth = (int) (options.outWidth / (float) width);
            int inSampleSizeHeight = (int) (options.outHeight / (float) height);
            options.inSampleSize = (inSampleSizeWidth > inSampleSizeHeight) ? inSampleSizeWidth : inSampleSizeHeight;
            if (options.inSampleSize < 1) {
                options.inSampleSize = 1;
            }
            return BitmapFactory.decodeFile(image.getAbsolutePath(), options);
        } catch (Exception e) {
            Log.d(TAG, "Exception", e);
            if(image!=null&&!image.equals(mCacheDir)){
                Log.d(TAG, String.format("--- Delete Invalid File[%s]",image.getAbsolutePath()));
                image.delete();
            }
            return null;
        }
    }
}
